
angular.module('checkGoods.controllers', [])

    .controller('HomeCtrl', ['$scope', 'UsbPortService', '$ionicModal', 'HomeService', '$ionicPopup','$cordovaToast', '$ionicLoading',
        function ($scope, UsbPortService,$ionicModal, HomeService, $ionicPopup, $cordovaToast, $ionicLoading) {
            // $scope.message = "";//二维码订单提示
            // $scope.exitMessage = "";//取货口提示
            // $scope.leftMessage = "";//信息提示
            //所有串口号
            $scope.ports = [];
            //所有取货口
            $scope.exits = ['广州','上海','北京'];
            var num = 1;
            $scope.data = {
                //选择的取货口
                selectExit:'上海',
                //选择的串口
                selectPort: '',
                //芯片id
                chipId:'',
                //车型
                car:'',
                carImage:'',
                //用户
                user:'',
                //头像
                userImage:'',
                //祝福语
                handText:'',
                //取货地址
                addressName:'',
                orderId:'',
                message:'',//二维码订单提示
                exitMessage :"",//取货口提示
                leftMessage :"",//信息提示
                leftChipMessage :"" //芯片信息提示
              
            };
            //芯片取货口信息
            var chip_address = "";
            //芯片订单号
            var chip_docno = "";
            //二维码订单号
            var barcode_docno = "";
            // var orderId = 1;
            //芯片数据：芯片ID,废品订单标识,订单ID,喷码内容,取货口,用户名称
            var chipData = "31 32 33 34 35 36 7C 30 7C 31 36 30 37 32 30 30 30 30 30 38 7C";
            // var chipData = "123456|0|16072000008|宝贝，我爱你|北京|张三";
            //二维码数据：订单地址，订单id，订单号，用户名，产品名称，取货口，废品标志位
            var barcodeData = "http://tapi.u9hub.com/so/2?id=2&docno=aaddcdafdadfd&user_nickname=user&product_name=car&address_name=北京&is_crap=0";
             
            $ionicModal.fromTemplateUrl('tpls/setting.html', {
                scope: $scope,
                animation: 'slide-in-right'
            }).then(function(modal) {
                $scope.modal = modal;
            });

            $ionicModal.fromTemplateUrl('tpls/settingExit.html', {
                scope: $scope,
                animation: 'slide-in-right'
            }).then(function(modal) {
                $scope.modalExit = modal;
            });

            // var GB2312UnicodeConverter = {
            //     ToUnicode: function (str) {
            //         return escape(str).toLocaleLowerCase().replace(/%u/gi, '\\u');
            //     }
            //     , ToGB2312: function (str) {
            //         return unescape(str.replace(/\\u/gi, '%u'));
            //     }
            // };
     
            // var str = '上海', unicode;
            // document.write(str + '<br/>');
            // unicode = GB2312UnicodeConverter.ToUnicode(str);
            // document.write('汉字转换为Unicode代码：' + unicode + '<br/><br/>');
            // document.write('Unicode代码转换为汉字：' + GB2312UnicodeConverter.ToGB2312(unicode));

                // HomeService.getOrderData("16072000008").then(function(data){
                //    if(data.data){
                //        $scope.data.car = data.data.product_name;
                //        $scope.data.user = data.data.user_nickname;
                //        $scope.data.userImage = data.data.user_avatar;
                //        $scope.data.carImage = data.data.product_image;
                //        $scope.data.handText = data.data.hand_text;
                //        $scope.data.addressName = data.data.address_name;
                //        chip_docno = data.data.docno;
                //        $scope.leftMessage = "你好，请扫描手机二维码验证取货";
                //    }
                //    else{
                //        $cordovaToast.showShortBottom("订单数据为空");
                //    }
                // },function(error){
                //   $cordovaToast.showShortBottom(error);
                   
                // });
            //0:已提交,1:待上线,2:已上线,3:已喷字,4:已质检, 5:已完工,6:待取货,7:已取货
            //网络获取芯片订单数据
            function getOrderData(orderId){
                $ionicLoading.show({
                    template: 'Loading...'
                });
                HomeService.getOrderData(orderId).then(function(data){
                   $scope.data.leftMessage = "";
                   $scope.data.leftChipMessage = '';
                   $scope.data.exitMessage = '';
                   $scope.data.message = '';
                   $ionicLoading.hide();
                   if(data.data){
                      if($scope.data.selectExit===''){
                         $cordovaToast.showShortBottom("请设置取货口");
                      }
                      else{
                         if(data.data.address_name===$scope.data.selectExit){
                         
                           $scope.data.car = data.data.product_name;
                           $scope.data.user = data.data.user_nickname;
                           $scope.data.userImage = data.data.user_avatar;
                           $scope.data.carImage = data.data.product_image;
                           $scope.data.handText = data.data.hand_text;
                           $scope.data.addressName = data.data.address_name;
                           var docno = data.data.docno;
                           var status = data.data.status;
                           var status_text = '';
                           if(status===0){
                              status_text = '已提交';
                           }
                           else if(status===1){
                              status_text = '待上线';
                           }
                           else if(status===2){
                              status_text = '已上线';
                           }
                           else if(status===3){
                              status_text = '已喷字';
                           }
                           else if(status===4){
                              status_text = '已质检';
                           }
                           else if(status===5){
                              status_text = '已完工';
                           }
                           else if(status===6){
                              status_text = '待取货';
                           }
                           else if(status===7){
                              status_text = '已取货';
                              $scope.data.leftMessage = "";
                           }
                           else if(status===10){
                              status_text = '已代取';
                              $scope.data.leftMessage = "";
                           }
                           else{
                              status_text = '无';
                           }
                           chip_docno = data.data.docno;
                           $scope.data.leftMessage = "你好，请扫描手机二维码验证取货";
                           $scope.data.leftChipMessage = "订单"+docno+"状态为："+status_text;

                         }
                      }
                       
                       
                   }
                   else{
                       $cordovaToast.showShortBottom("订单数据为空");
                   }

                   
                },function(error){
                   $ionicLoading.hide();
                   $cordovaToast.showShortBottom(error);
                });
            }
            //网络获取二维码订单数据
            function getBarcodeOrderData(orderId){
                $ionicLoading.show({
                    template: 'Loading...'
                });
                HomeService.getOrderData(orderId).then(function(data){
                   $ionicLoading.hide();
                   $scope.data.exitMessage = '';
                   $scope.data.message = '';
                   if(data.data){
                       barcode_docno = data.data.docno;
                       var status = data.data.status;

                       if(barcode_docno===chip_docno){
                          if(status===7){
                            $scope.data.message = "订单"+barcode_docno+"已经取货";
                          }
                          else if(status===10){
                            $scope.data.message = "订单"+barcode_docno+"已超过取货时限，已由服务人员代取，请和服务人员联系进行取货";
                          }
                          else{
                            $scope.data.message = "验证通过，请取货。";
                            $ionicLoading.show({
                                template: 'Loading...'
                            });
                            HomeService.updateOrderStatus(orderId,7).then(function(data){
                                $ionicLoading.hide();
                                if(data){
                                   $cordovaToast.showShortBottom("更新订单状态成功");
                                }
                                else{
                                   $cordovaToast.showShortBottom("更新订单状态失败");
                                }
                                $ionicLoading.hide();  
                            },function(error){
                                $ionicLoading.hide();
                                $cordovaToast.showShortBottom(error);
                            });
                          }
                          

                       }
                       //0:已提交,1:待上线,2:已上线,3:已喷字,4:已质检, 5:已完工,6:待取货,7:已取货
                       else{
                          // var exit = '';
                          if(data.data.address_name===$scope.data.selectExit){
                               $scope.data.exitMessage = '';
                          }
                          else{
                               $scope.data.exitMessage = "此取货口为"+$scope.data.selectExit+"，请到"+data.data.address_name+"取货口取货";
                          }
                          if(status===7){
                            $scope.data.message = "订单"+barcode_docno+"已经取货";
                          }
                          else if(status===10){
                            $scope.data.message = "订单"+barcode_docno+"已超过取货时限，已由服务人员代取，请和服务人员联系进行取货";
                          }
                          else{
                            $scope.data.message = "订单"+barcode_docno+"，还未加工完毕，请耐心等待";
                          }
                       }
                   }
                   else{
                       $cordovaToast.showShortBottom("订单数据为空");
                   }
                   
                },function(error){
                   $ionicLoading.hide();
                   $cordovaToast.showShortBottom(error);
                });
            }
            //获取芯片数据
            function getChipData(data){
                var chip_data = data.split("7C");
                // $scope.data.chipId = chip_data[0];
                // var orderId = parseInt(chip_data[2]);
                var order_data = chip_data[2].split(" ");
                var order_id = '';
                for (var i = 1; i < order_data.length-1; i++) {
                     order_id = order_id + String.fromCharCode(parseInt(order_data[i],16));
                }

                getOrderData(order_id);
                   
            }
            
            // getChipData(chipData);
            // window.localStorage.setItem("port", angular.toJson("/dev/ttymxc1"));


            document.addEventListener("deviceready", function() {
                if (cordova.plugins.SerialPort) {
                    var port = angular.fromJson(window.localStorage.getItem("port"));
                    $cordovaToast.showShortBottom(port);
                    
                    if (port == null) {
                        $scope.$on('serialport.DataReceived', function (e, data) {
                          $cordovaToast.showShortBottom(data);
                             
                             if(data){
                                if(num===1){
                                    window.localStorage.setItem("port", angular.toJson($scope.data.selectPort));
                                    // $ionicPopup.alert({
                                    //    title: '串口设置成功',
                                    //    template: '无需设置'
                                    // });
                                    getChipData(data);
                                    
                                    num++;
                                }else{
                                    getChipData(data);
                                    
                                }
                                
                             }
                             else{
                                cordova.plugins.SerialPort.close();
                             }    
                        });

                    }
                    else{
                        // $ionicPopup.alert({
                        //    title: '串口设置成功',
                        //    template: '无需设置'
                        // });
                        $scope.data.selectPort = port;
                        cordova.plugins.SerialPort.open($scope.data.selectPort, {}, function () {
                        
                        }, function () {
                            $cordovaToast.showShortBottom("打开串口失败");
      
                        });
                        $scope.$on('serialport.DataReceived', function (e, data) {
                          $cordovaToast.showShortBottom(data);
                            
                            getChipData(data);
              
                        });
                    }
                    
                    
                }
                
            }, false);
            
            $scope.setOrderId = function(){
               // 一个精心制作的自定义弹窗
               var myPopup = $ionicPopup.show({
                 template: '<input type="text" ng-model="data.orderId">',
                 title: '编辑订单id',
                 subTitle: '输入订单id',
                 scope: $scope,
                 buttons: [
                   { text: '取消' },
                   {
                     text: '保存',
                     type: 'button-positive',
                     onTap: function(e) {
                        getOrderData($scope.data.orderId);
                     }
                   },
                 ]
               });
            };

            $scope.setExit = function(){
                $scope.modalExit.show().then(function () {
                    // $scope.$apply();
                });
            };

            $scope.showPorts = function(){
                if (cordova.plugins.SerialPort) {
                    cordova.plugins.SerialPort.getAllDevices(function(ports) {
                        $scope.ports = ports;
                        $scope.modal.show().then(function () {
                            // $scope.$apply();
                        });   
                    }, function(error) {
                        $cordovaToast.showShortBottom("获取设备的端口号失败"+error);
                    });
                }   
            };

            $scope.getOneExit = function(item){
                $scope.data.selectExit = item;
                $scope.modalExit.hide();

            };

            $scope.getOnePort = function(port){
                $scope.data.selectPort = port;
                cordova.plugins.SerialPort.open(port, {}, function () {
                    $scope.modal.hide();
                }, function () {
                  $cordovaToast.showShortBottom("打开串口失败");
                });
            };
           
            $scope.$on('$ionicView.beforeEnter', function() {
                UsbPortService.start();
            });
            $scope.$on('$ionicView.afterLeave', function() {
                cordova.plugins.SerialPort.close();
                UsbPortService.stop();
            });
            $scope.$on('UsbPortService.input', function(e, inputStr) {
                var orderId='';
                if(inputStr.indexOf("&id")>=0)
                {
                  orderId = inputStr.substring(inputStr.indexOf("&id")+4);
                }
                if(inputStr.indexOf("&ID")>=0)
                {
                  orderId = inputStr.substring(inputStr.indexOf("&ID")+4);
                }
                
                // var orderId = barcodeData.substring(barcodeData.indexOf("id")+3, barcodeData.indexOf("&"));
                getBarcodeOrderData(orderId);
            });
        }
    ]);